/* main.c, Ait, BSD 3-Clause, Kevin Bloom, 2023,
   Derived from: Atto January 2017
   Derived from: Anthony's Editor January 93
*/

#include "header.h"
#include "termbox.h"
#include "util.h"

int done;
point_t nscrap;
char_t *scrap;

char_t *input;
int msgflag;
char msgline[TEMPBUF];
char temp[TEMPBUF];
char searchtext[STRBUF_M];
char replace[STRBUF_M];
int found_point = -1;
int search_dir = 1;
int universal_argument = 0;
int numeric_argument = 0;
int negated = FALSE;
int submatch = 0;
uint32_t input_char = 0;
int undoset_flag = FALSE;
char editor_dir[NAME_MAX+1];
int record_input = FALSE;
int record_buffer_index = 0;
int run_buffer_index = 0;
struct tb_event record_buffer[256];
int execute_kbd_macro = FALSE;
int undo_index = -1;
char unicode_buf[7];
char character[1];
int lastcommand = KBD_DEFAULT;
int currentcommand = KBD_DEFAULT;
int window_mode = WINDOW_DEFAULT;

keymap_t *key_return;
keymap_t *key_map;
buffer_t *curbp;   /* current buffer */
buffer_t *bheadp;   /* head of list of buffers */
window_t *curwp;
window_t *wheadp;
buffer_t *lastbp = NULL;  /* last active buffer */
int LINES;
int COLS;
int MSGLINE;

static void graceful_exit()
{
  tb_shutdown();
  exit(1);
}

static void cont()
{
  tb_init();
  LINES = tb_height();
  COLS = tb_width();
  MSGLINE = LINES-1;
  tb_set_input_mode(TB_INPUT_ALT);
  tb_clear();
  redraw();
  update_display();
}

static void setup_signal_handlers()
{
  struct sigaction action;

  memset(&action, 0, sizeof(struct sigaction));

  action.sa_handler = graceful_exit;
  sigaction(SIGTERM, &action, NULL);
  sigaction(SIGINT, &action, NULL);
  sigaction(SIGQUIT, &action, NULL);
  sigaction(SIGHUP, &action, NULL);

  action.sa_handler = cont;
  sigaction(SIGCONT, &action, NULL);

  signal(SIGPIPE, SIG_IGN);
}

int main(int argc, char **argv)
{
  int ret, u, buffers = 0;
  int line = 0, current = 0, lastln = 0;
  point_t p;

  if(1 < argc && argv[1][0] == '-') {
    if(argv[1][1] == 'v') {
      fprintf(stderr, "%s\n", VERSION);
      exit(0);
    }
    if(argv[1][1] == 'h') {
      fprintf(stderr, "%s\n\nUsage: ait [options] [file]... +/-line...\n\n\n-h     Print help and exit\n-v     Print version and exit\n", VERSION);
      exit(0);
    }
  }

  ret = tb_init();
  LINES = tb_height();
  COLS = tb_width();
  MSGLINE = LINES-1;
  character[0] = '\0';
  if (ret) {
    fprintf(stderr, "Failed with error code %d", ret);
    exit(1);
  }

  getcwd(editor_dir, sizeof(editor_dir));
  strcat(editor_dir, "/");

  tb_set_input_mode(TB_INPUT_ALT);
  tb_clear();

  setup_signal_handlers();

  if (1 < argc) {
    for(int v = 1; v < argc; v++) {
      buffers++;
      curbp = find_buffer(argv[v], TRUE);
      (void) insert_file(argv[v], FALSE);
      /* Save filename regardless of load() success. */
      if(argv[v][0] == '/') {
        strncpy(curbp->b_fname, argv[v], NAME_MAX);
      } else {
        strncpy(curbp->b_fname, editor_dir, NAME_MAX);
        strcat(curbp->b_fname, argv[v]);
        cleanup_path(curbp->b_fname, curbp->b_fname);
      }
      curbp->b_fname[NAME_MAX] = '\0'; /* force truncation */
      curbp->b_path = TRUE;
      curbp->b_line = 1;
      if(argv[v+1]) {
        if(argv[v+1][0] == '-' || argv[v+1][0] == '+') {
          if(argv[v+1][0] == '+') {
            argv[v+1]++;
            line = atoi(argv[v+1]);
          } else {
            argv[v+1]++;
            get_line_stats(&current, &lastln, curbp);
            line = lastln - atoi(argv[v+1]);
            if(line < 0)
              line = 0;
          }
          p = line_to_point(line);
          if (p != -1) {
            curbp->b_point = p;
            if (curbp->b_epage < pos(curbp, curbp->b_ebuf)) curbp->b_reframe = 1;
            curbp->b_line = line;
            msg("Line %d", line);
          } else {
            msg("Line %d, not found", line);
          }
          v++;
        }
      }
    }
  } else {
   curbp = find_buffer("*scratch*", TRUE);
   strncpy(curbp->b_bname, "*scratch*", STRBUF_S);
   curbp->b_path = FALSE;
  }

  if (!growgap(curbp, CHUNK))
    fatal("%s: Failed to allocate required memory.\n");

  movegap(curbp, 0);
  key_map = keymap;

  submatch = 0;
  wheadp = curwp = new_window();
  associate_b2w(curbp, curwp);
  one_window(curwp);
  if(buffers > 1) {
    chop_window();
    next_buffer();
  }
  while (!done) {
    update_display();
    curbp->b_opoint = curbp->b_point;
    input = get_key(key_map, &key_return);
    if (key_return != NULL) {
      /* TODO: a better way to figure out editing commands */
      if((key_return->key_desc[2] == 'd' || key_return->key_desc[4] == '%' ||
          key_return->key_desc[2] == 'i' || key_return->key_desc[2] == 'k' ||
          key_return->key_desc[2] == '/' || key_return->key_desc[2] == 'm' ||
          key_return->key_desc[2] == 't' || key_return->key_desc[2] == 'y' ||
          key_return->key_desc[4] == 'd' || key_return->key_desc[4] == 'i' ||
          key_return->key_desc[4] == 't' || key_return->key_desc[4] == 'x' ||
          key_return->key_desc[4] == 'k' || key_return->key_desc[4] == '/' ||
          key_return->key_desc[4] == 'l' || key_return->key_desc[4] == 'c' ||
          key_return->key_desc[4] == 'u' || key_return->key_desc[4] == 'z' ||
          key_return->key_desc[4] == 'Z' || (key_return->key_desc[4] == 'b'
          && key_return->key_desc[5] == 'k') || key_return->key_desc[2] == 'h') &&
        is_file_modified(curbp->b_fname)) {
        if(!file_was_modified_prompt()) {
          continue;
        }
      }
      submatch = 0;
      if(execute_kbd_macro) {
        (key_return->func)();
      } else {
        u = numeric_argument > 0 ? numeric_argument : power(4, universal_argument);
        if(numeric_argument > 0 &&
         key_return->universal_argument_action != UA_PREVENT)
        key_return->universal_argument_action = UA_REPEAT;
         switch(key_return->universal_argument_action) {
        case UA_REPEAT:
          for(; u > 0; u--)
            (key_return->func)();
          universal_argument = 0;
          numeric_argument = 0;
          /* For gotochar */
          character[0] = '\0';
          break;
        default:
          (key_return->func)();
          break;
        }
      }
      if(temp[0] != 0)
        memset(temp, 0, TEMPBUF);
    } else if(submatch > 0) {
      // do nothing
    } else {
      submatch = 0;
      if((unicode_buf[0] != '\0' || *input > 31 || *input == 13 || *input == 9)
         && is_file_modified(curbp->b_fname)) {
        if(!file_was_modified_prompt()) {
          continue;
        }
      }
      /* allow TAB and NEWLINE, otherwise any Control Char is 'Not bound' */
      if(unicode_buf[0] != '\0') {
        u = numeric_argument > 0 ? numeric_argument : power(4, universal_argument);
        char tempbuf[7];
        strncpy(tempbuf, unicode_buf, 7);
        for(; u > 0; u--) {
          unicode_buf[0] = tempbuf[0];
          insert_unicode();
        }
      }
      else
        msg("Not bound");
    }
    if(currentcommand != KBD_DELETE_CHAR &&
       currentcommand != KBD_CUT &&
       currentcommand != KBD_UNDO
       ) {
      if(curbp->b_opoint > curbp->b_point) {
        curbp->b_opoint--;
        while(curbp->b_opoint >= curbp->b_point) {
          if(*ptr(curbp, curbp->b_opoint) == '\n')
            curbp->b_line--;
          curbp->b_opoint--;
        }
      } else if(curbp->b_opoint < curbp->b_point) {
        while(curbp->b_opoint < curbp->b_point) {
          if(*ptr(curbp, curbp->b_opoint) == '\n')
            curbp->b_line++;
          curbp->b_opoint++;
        }
      }
    }
    if(currentcommand != lastcommand)
      lastcommand = currentcommand;
    currentcommand = KBD_DEFAULT;
  }

  if (scrap != NULL) free(scrap);
  tb_set_cursor(0, LINES-1);
  tb_present();
  tb_shutdown();
  return 0;
}

void fatal(char *msg)
{
  tb_present();
  fprintf(stderr, msg, PROG_NAME);
  exit(1);
}

void msg(char *msg, ...)
{
  va_list args;
  va_start(args, msg);
  (void)vsprintf(msgline, msg, args);
  va_end(args);
  msgflag = TRUE;
}
